package com.vectz.mgt.action;

import java.io.IOException;
import java.util.ArrayList;

import com.vectz.mgt.model.Entity;
import com.vectz.mgt.model.EntityOverview;
import com.vectz.mgt.util.Constant;
import com.vectz.mgt.util.Log;
import com.vectz.mgt.util.Util;

/**
 * @author ai-t.vn
 * 
 */
public class JsfListCodegenAction {
	ArrayList<Entity> listField = null;
	EntityOverview table = null;
	String outputFolder = "";
	int numColDisplayListPage = 0;
	public JsfListCodegenAction(ArrayList<Entity> listField,
			EntityOverview table, String outputFolder) throws Exception{
		this.listField = listField;
		this.table = table;
		this.outputFolder = outputFolder;
		genernateJsfFile();
	}

	/*
	 * Generate jsf file
	 */
	public void genernateJsfFile()  throws Exception{
			String tmplFormContent = Util.readTextFileContent(Util.getTmplPath(
					"jsf", "Form-ListEntity.txt"));
			String tmplFieldContent = Util.readTextFileContent(Util
					.getTmplPath("jsf", "ListEntityData.txt"));

			String tmplFieldHeader = Util.readTextFileContent(Util.getTmplPath(
					"jsf", "ListEntityHeader.txt"));

			tmplFormContent = tmplFormContent.replaceAll("xxxxFormId", Util.isEmpty(table
					.getScreenId())? table.getName():table.getScreenId());

			tmplFormContent = tmplFormContent.replaceAll("xxxxInitNew", Util
					.buildButtonAction(table.getName(), "initNew"));
			tmplFormContent = tmplFormContent.replaceAll("xxxxInitModify", Util
					.buildButtonAction(table.getName(), "initModify"));
			tmplFormContent = tmplFormContent.replaceAll("xxxxInitDelete", Util
					.buildButtonAction(table.getName(), "delete"));
			tmplFormContent = tmplFormContent.replaceAll("xxxxEntityId",
					getIdField(listField));
			/*
			 * Add datascroller object when set number of page param
			 * Modify at 2008-10-28 by anhdv 
			 */
			if(!Util.isEmpty(table.getNumRecordDisplay())){
				
				tmplFormContent = tmplFormContent.replaceAll("xxxxRow", "rows=\""
						+ String.valueOf(new Double(table.getNumRecordDisplay().trim()).intValue())+"\"");
				
			}else{
				tmplFormContent = tmplFormContent.replaceAll("xxxxRow", "");
			}
			if(!Util.isEmpty(table.getNumPageDisplay())) {
				tmplFormContent = tmplFormContent.replaceAll("xxxxDatascroller", new StringBuffer()
						.append("<rich:datascroller align=\"center\" for=\"myDataTable\" maxPages=\"")
						.append(String.valueOf(new Double(table.getNumPageDisplay().trim()).intValue())+"\" renderIfSinglePage=\"false\" />").toString());
			}else{	
				tmplFormContent = tmplFormContent.replaceAll("xxxxDatascroller","");
			}
			tmplFormContent = tmplFormContent.replaceAll("xxxxItem", Util
					.lowerCaseFirstChar(table.getName()));
			

			// replace column header
			String listHeaderColumn = genernateHeaderColumn(listField,
					tmplFieldHeader);
			tmplFormContent = tmplFormContent.replaceAll("xxxxColumnHeader",
					listHeaderColumn);

			// add column data
			String listFieldForm = genernateColumn(listField, tmplFieldContent);
			tmplFormContent = tmplFormContent.replaceAll("xxxxColumnData",
					listFieldForm);
			
			// initial list column width
			if (numColDisplayListPage!= 0) {
				// first column width
				String arrayWidth = "4%";
				// calculate column width for another column 
				int widthAverage = 96 / numColDisplayListPage;
				for (int i = 0; i < numColDisplayListPage; i++) {
					arrayWidth += new StringBuffer().append(",").append(
							widthAverage).append("%");

				}
				tmplFormContent = tmplFormContent.replaceAll("xxxxArrayWidth",
						arrayWidth);
			}else{
				tmplFormContent = tmplFormContent.replaceAll("xxxxArrayWidth",
						"4%");
			}
			
			String fileLocation = new StringBuffer().append(outputFolder)
					.append(System.getProperty("file.separator")).append(
							"WebContent").append(
							System.getProperty("file.separator")).append(
							Util.getWebbaseDir(table.getDestScreenPath()))
					.append(System.getProperty("file.separator")).append(
							Util.lowerCaseFirstChar(table.getName())).append(
							"List.xhtml").toString();

			Util.writeJavaFile(fileLocation, tmplFormContent);
			Log.log("Finish generate jsf file to:" + fileLocation);
	}

	/*
	 * Generate header name of column
	 */
	public String genernateHeaderColumn(ArrayList<Entity> listField,
			String tmplContent) {
		StringBuffer content = new StringBuffer();
		if (listField == null && listField.size() == 0)
			return "";
		Entity field = null;
		for (int i = 0; i < listField.size(); i++) {
			field = (Entity) listField.get(i);
			/* check only displayInListPage=show and displayInEditPage=show
			 * then add new component
			 * Modify at 20081031 by anhdv 
			 */
			if (field.getDisplayInListPage().equalsIgnoreCase("show")
					&& field.getDisplay().equalsIgnoreCase("show")) {
				numColDisplayListPage ++;
				String tmp = tmplContent;
				tmp = tmp.replaceAll("xxxxHeader",field.getLogicalName());
				content.append(tmp);
			}
		}

		return content.toString();
	}

	/*
	 * Generate header value of column
	 */
	public String genernateColumn(ArrayList<Entity> listField,
			String tmplContent) {
		StringBuffer content = new StringBuffer();
		if (listField == null && listField.size() == 0)
			return "";
		Entity field = null;
		for (int i = 0; i < listField.size(); i++) {
			field = (Entity) listField.get(i);
			/* check only displayInListPage=show and displayInEditPage=show
			 * then add new component
			 * Modify at 20081031 by anhdv 
			 */
			if (field.getDisplayInListPage().equalsIgnoreCase("show") 
					&& field.getDisplay().equalsIgnoreCase("show")) {

				String tmp = "";
				// check if inputDataType = DateTime
				// Modify by anhdv 2008-10-21
				if (field.getInputType().equalsIgnoreCase("DateTime")) {
					tmp = new StringBuffer()
					.append("<rich:column styleClass=\"rich-column-center\">")
					.append("<gmt:periodDateTime id=\"_" + field.getName() +"\" value=")
					.append(getInputValue(field))
					.append(" labelFlg=\"true\" required=\"true\"/>")
					.append("</rich:column>")
					.toString();
				}
				/* Check if form has fileUpload component then not allows display 	
				 * Modify by anhdv 2008-10-23
				 */ 
				else if (field.getInputType().equalsIgnoreCase("fileUpload")) {
					tmp = new StringBuffer()
							.append("<rich:column styleClass=\"rich-column-center\">")
							.append("</rich:column>").toString();
				}
				// if inputType is selectManyCheckbox then add tag <ui:repeat>
				// Modify by anhdv 2008-10-20
				else {
					tmp = tmplContent;
					if (field.getInputType() != null
							&& field.getInputType().equalsIgnoreCase(
									"selectManyCheckbox")) {
						// start <ui:repeat>
						tmp = tmp.replaceAll("xxxxStartRepeat",
								new StringBuffer().append("<ui:repeat value=")
										.append(getInputValue(field)).append(
												" var=\"item\"><li>")
										.toString());
						// loop content
						tmp = tmp.replaceAll("xxxxOuputValue", "\"#{item}\"");
						// end <ui:repeat>
						tmp = tmp.replaceAll("xxxxEndRepeat",
								"</li></ui:repeat>");

						tmp = tmp.replaceAll("xxxxFormatItem", "");
					} else {
						tmp = tmp.replaceAll("xxxxStartRepeat", "");
						tmp = tmp.replaceAll("xxxxEndRepeat", "");
						tmp = tmp.replaceAll("xxxxOuputValue",
								getInputValue(field));
						// check if inputDataType = Time then convert to HH:mm pattern
						if (field.getInputType().equalsIgnoreCase("Time")) {

							tmp = tmp
									.replaceAll("xxxxFormatItem",
											"<s:convertDateTime pattern=\"HH:mm\" type=\"time\" />");
						}
						// check if inputDataType = Date then convert to datetime pattern
						else if (field.getInputType().equalsIgnoreCase("Date")) {
							if (!Util.isEmpty(field.getDescription()))
								tmp = tmp.replaceAll("xxxxFormatItem",
										"<f:convertDateTime pattern=\""	+ field.getDescription()+ "\"/>");
							else
								// default format date: YYYY/MM/DD
								tmp = tmp
										.replaceAll("xxxxFormatItem",
												"<f:convertDateTime pattern=\"yyyy/MM/dd\"/>");
						} else {
							tmp = tmp.replaceAll("xxxxFormatItem", "");
						}
					}
				}// end else check if inputDataType = DateTime
				content.append(tmp);
			}
			
		}
	
		

		return content.toString();
	}

	/*
	 * Generate Id field in model class
	 */
	public String getIdField(ArrayList<Entity> listField) {
		if (listField == null && listField.size() == 0)
			return "";
		Entity field = null;
		for (int i = 0; i < listField.size(); i++) {
			field = (Entity) listField.get(i);
			if (field.getKeyType().equalsIgnoreCase("PK")) {
				return new StringBuffer()
						// .append(Util.lowerCaseFirstChar(table.getName()))
						// .append("Action.")
						.append(Util.lowerCaseFirstChar(table.getName()))
						.append(".").append(field.getName()).toString();
			}
		}
		return "";
	}

	/**
	 * Get input value with pattern: #{entityAction.entity.field}
	 * 
	 * @param entity
	 * @return input value
	 */
	public String getInputValue(Entity entity) {
		return new StringBuffer().append("\"#{").append(
				Util.lowerCaseFirstChar(table.getName())).append(".").append(
				Util.lowerCaseFirstChar(entity.getName())).append("}\"")
				.toString();
	}
}
